<template>
  <div class="test-step-content">
    <!-- 左右布局容器 -->
    <div class="content-wrapper">
      <!-- 左侧：完成签约办理 + 图片上传 -->
      <div class="left-content">
        <div class="sign-container">
          <h2 class="sign-title">完成签约办理</h2>
          <!-- 签约信息模块 -->
          <div class="sign-module">
            <div class="sign-header">
              <span class="sign-tag">1</span>
              <span class="sign-info">签约信息</span>
            </div>
            <div class="form-row">
              <label class="form-label">合同编号</label>
              <span class="form-value">{{ contractNo }}</span>
            </div>
            <div class="form-row">
              <label class="form-label-required">合同名称</label>
              <el-input
                v-model="contractName"
                placeholder="请输入"
                max-length="20"
                show-word-limit
                style="width: 240px"
              />
            </div>
            <div class="form-row">
              <label class="form-label">合同期限</label>
              <span class="form-value">{{ startDate }} —— {{ endDate }}</span>
            </div>
            <div class="form-row">
              <label class="form-label-required">签约日期</label>
              <el-date-picker
                v-model="signDate"
                type="date"
                value-format="YYYY-MM-DD"
                style="width: 240px"
                :disabled-date="disablePastDates"
              />
            </div>
            <div class="form-row">
              <label class="form-label">丙方姓名</label>
              <el-input
                v-model="thirdPartyName"
                placeholder="请输入"
                max-length="10"
                show-word-limit
                style="width: 240px"
              />
            </div>
            <div class="form-row">
              <label class="form-label">丙方联系方式</label>
              <el-input
                v-model="thirdPartyPhone"
                placeholder="请输入"
                max-length="11"
                show-word-limit
                style="width: 240px"
              />
            </div>
            <div class="form-row">
              <label class="form-label-required">上传合同</label>
              <div class="upload-container">
                <el-button
                  type="primary"
                  @click="selectFile"
                  icon="Upload"
                  style="width: 140px; justify-content: center"
                >
                  选择图片上传
                </el-button>
                <input
                  ref="fileInput"
                  type="file"
                  class="hidden"
                  accept="image/jpeg,image/png"
                  @change="handleFileChange"
                />
                <el-progress
                  v-if="progress > 0 && progress < 100"
                  :percentage="progress"
                  style="width: 240px; margin-top: 10px"
                />
                <div
                  v-if="imageUrl && selectedFileName"
                  class="file-info-group"
                >
                  <span class="uploaded-file-name">{{ selectedFileName }}</span>
                  <el-button
                    type="text"
                    @click="previewImage"
                    style="margin-left: 12px; color: #409eff; cursor: pointer"
                  >
                    预览
                  </el-button>
                </div>
                <p v-if="!imageUrl && uploadHint" class="upload-hint">
                  请上传合同图片
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：操作记录区域 -->
      <div class="right-content">
        <el-card class="operation-record-card">
          <h3>操作记录</h3>
          <ul class="record-list">
            <li>
              <div class="record-item">
                <div class="record-icon"></div>
                <div class="record-content">
                  <p>评估中-健康信息录入</p>
                  <p>{{ lastName1 }} (已完成)</p>
                </div>
                <div class="record-time">{{ lastTime1 }}</div>
              </div>
            </li>
            <li>
              <div class="record-item">
                <div class="record-icon"></div>
                <div class="record-content">
                  <p>审批-入住审批</p>
                  <p>{{ lastName2 }} (已通过)</p>
                </div>
                <div class="record-time">{{ lastTime2 }}</div>
              </div>
            </li>
            <li>
              <div class="record-item">
                <div class="record-icon"></div>
                <div class="record-content">
                  <p>配置-入住配置</p>
                  <p>{{ lastName3 }} (已完成)</p>
                </div>
                <div class="record-time">{{ lastTime3 }}</div>
              </div>
            </li>
            <li>
              <div class="record-item">
                <div class="record-icon"></div>
                <div class="record-content">
                  <p>签约办理-合同签约</p>
                  <p>{{ userStore.nickName }} (进行中)</p>
                </div>
                <div class="record-time">{{ currentTime }}</div>
              </div>
            </li>
          </ul>
        </el-card>
      </div>
    </div>

    <!-- 底部按钮组 -->
    <div class="btn-group">
      <el-button @click="handleGoBack" size="default" plain class="mr-3">
        返回
      </el-button>
      <el-button type="primary" @click="handleSubmit" size="default">
        提交
      </el-button>
    </div>
  </div>
</template>
  
  <script setup>
import { ref, onMounted, watch, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";
import { getElderly1 } from "@/api/system/elderly";
import { getRuzhuByElder } from "@/api/rutui/ruzhu";
import { addContract } from "@/api/system/contract";
import { numberGeneration } from "@/utils/numberGeneration";
import { getReport } from "@/api/assessreport/report"; //查询评估报告
import { getUniqueRecord } from "@/api/accraditationrecord/accraditationrecord";
import { getUser } from "@/api/system/user";
import axios from "axios";
import { updateAccraditationrecord } from "@/api/accraditationrecord/accraditationrecord"; //修改步骤状态
import { get } from "@vueuse/core";

// 原有逻辑：当前登录用户信息打印
const userStore = useUserStore();
console.log("当前登录用户信息：", {
  id: userStore.id,
  name: userStore.name,
  nickName: userStore.nickName,
  avatar: userStore.avatar,
  roles: userStore.roles,
  permissions: userStore.permissions,
});
// 接收父组件参数
const props = defineProps({
  stepNum: {
    type: Number,
    required: true,
  },
  elderlyId: {
    type: Number,
    required: true,
  },
});
const elderId = props.elderlyId;
const currentTime = ref("");
let timer = null; // 存储定时器，用于组件卸载时清除

const formatTime = (date) => {
  // 同上，格式化时间
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const lastTime1 = ref("");
const lastTime3 = ref("");
const userId1 = ref("");
const lastName1 = ref("");
const userId3 = ref("");
const lastName3 = ref("");
// 3. 单独查询“评估报告”函数（核心：解析levelChangeBasis和otherBasis）
const queryAssessReport = async () => {
  try {
    const res = await getReport(elderId);
    const res1 = await getRuzhuByElder(elderId);
    console.log("=== 评估报告原始数据 ===");
    console.log("原始数据：", res.data);
    lastTime1.value = res.data?.createTime || "无";
    lastTime3.value = res1.data?.createTime || "无";
    userId1.value = res.data?.creator || "无";
    userId3.value = res1.data?.creator || "无";
    // 调用 getUser 接口获取用户信息
    const userRes1 = await getUser(userId1.value);
    const userRes3 = await getUser(userId3.value);
    lastName1.value = userRes1.data?.nickName || "无";
    lastName3.value = userRes3.data?.nickName || "无";
  } catch (error) {
    console.error("评估报告查询失败：", error);
  }
};

// 表单响应式变量
const contractNo = ref("");
const contractName = ref("");
const signDate = ref("");
const thirdPartyName = ref("");
const thirdPartyPhone = ref("");
const formInfo = ref({});
const startDate = ref("");
const endDate = ref("");
const uploadHint = ref(false);

// 合同状态相关变量
const contractStatus = ref(""); // 待生效/生效中/已过期
const statusClass = ref(""); // 状态样式（不同状态不同颜色）

// 图片上传相关变量：新增selectedFileName存储完整文件名
const fileInput = ref(null);
const progress = ref(0);
const imageUrl = ref("");
const selectedFile = ref(null);
const selectedFileName = ref(""); // 存储上传文件的完整名称

// 1. 核心：生成合同编号（身份证后四位+今日日期+两位随机数）
const generateContractNo = () => {
  contractNo.value = numberGeneration("HT");
  console.log("生成的合同编号：", contractNo.value);
};

// 2. 计算合同状态的核心函数
const calculateContractStatus = () => {
  if (!signDate.value || !startDate.value || !endDate.value) {
    contractStatus.value = "";
    statusClass.value = "";
    return;
  }

  const signTimestamp = new Date(signDate.value).getTime();
  const startTimestamp = new Date(startDate.value).getTime();
  const endTimestamp = new Date(endDate.value).getTime();

  if (signTimestamp < startTimestamp) {
    contractStatus.value = "待生效";
    statusClass.value = "status-pending";
  } else if (signTimestamp >= startTimestamp && signTimestamp <= endTimestamp) {
    contractStatus.value = "生效中";
    statusClass.value = "status-active";
  } else {
    contractStatus.value = "已过期";
    statusClass.value = "status-expired";
  }
};

// 3. 监听日期变化，自动更新状态
watch(
  [() => signDate.value, () => startDate.value, () => endDate.value],
  () => {
    calculateContractStatus();
  }
);

// 4. 必填项校验函数
const checkRequired = (value, name) => {
  if (!value || value.trim() === "") {
    ElMessage.warning(`${name}为必填项`);
    return false;
  }
  return true;
};

// 5. 手机号格式校验（仅提交时）
const checkPhoneFormat = () => {
  const phone = thirdPartyPhone.value.trim();
  if (!phone) return true; // 非必填，空值通过

  const reg = /^1[3-9]\d{9}$/;
  if (!reg.test(phone)) {
    ElMessage.warning("请输入有效的11位手机号码");
    return false;
  }
  return true;
};

// // 6. 查询老人信息函数（获取身份证后生成合同编号）
// const queryElderlyInfo = async () => {
//   try {
//     const res = await getElderly1(elderId);
//     const idCard = res.data.idCard || "";
//     console.log("身份证号码：", idCard);
//     // 关键：获取身份证后调用编号生成函数
//     generateContractNo(idCard);
//   } catch (error) {
//     console.error("老人信息查询失败：", error);
//     // 失败时用默认值生成编号
//     generateContractNo("");
//   }
// };

// 7. 禁止选择今天之前的日期（签约日期）
const disablePastDates = (time) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};
const lastTime2 = ref("");
const userId2 = ref("");
const lastName2 = ref("");
const recordData = ref(null);
onMounted(async () => {
  // 1. 等待用户信息加载完成（确保 token 可用）
  await new Promise(resolve => {
    const checkUser = () => {
      if (userStore.token) {
        resolve();
      } else {
        // 每 100ms 检查一次，最多等 5 秒
        setTimeout(checkUser, 100);
      }
    };
    checkUser();
  });
  // 2. 确保 elderId 有效
  if (!elderId) {
    ElMessage.warning("未获取到老人ID，无法加载数据");
    return;
  }

  // 3. 执行原有初始化逻辑
  // queryElderlyInfo(); // 查询老人信息生成合同编号
  generateContractNo(); // 生成合同编号
  queryAssessReport(); // 查询评估报告

  // 4. 获取合同时间
  try {
    const res = await getRuzhuByElder(elderId);
    const startDateObj = new Date(res.data.feeStartDate);
    startDate.value = startDateObj
      .toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
      })
      .replace(/\//g, "-");

    const endDateObj = new Date(res.data.feeEndDate);
    endDate.value = endDateObj
      .toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
      })
      .replace(/\//g, "-");

    calculateContractStatus();
  } catch (error) {
    console.error("获取合同时间失败：", error);
  }

  // 5. 核心：查询审批记录（整合到 onMounted）
  try {
    const query = {
      stepNo: 5,
      checkContentId: elderId
    };
    console.log("查询审批记录参数：", query);
    const response = await getUniqueRecord(query);
    recordData.value = response.data || response;
    console.log("审批记录数据：", recordData.value);

    // 6. 处理审批人信息
    userId2.value = recordData.value?.approverId || "无";
    lastTime2.value = recordData.value?.createTime || "无";
    
    if (userId2.value && userId2.value !== "无") {
      const userRes2 = await getUser(userId2.value);
      lastName2.value = userRes2.data?.nickName || "无";
    } else {
      lastName2.value = "无";
    }
  } catch (error) {
    console.error("获取审批记录失败：", error);
    // 失败时给默认值，避免页面空白
    userId2.value = "无";
    lastName2.value = "无";
    lastTime2.value = "无";
    // 可添加重试逻辑（视业务需求）
    // setTimeout(() => {/* 重试逻辑 */}, 1000);
  }

  // 7. 初始化当前时间
  currentTime.value = formatTime(new Date());
  timer = setInterval(() => {
    currentTime.value = formatTime(new Date());
  }, 1000);

});
const updateApprovalRecord = async (recordData) => {
  // 校验记录是否有效
  if (!recordData || !recordData.id) {
    ElMessage.warning("未获取到有效的审批记录，无法修改");
    return false;
  }

  try {
    // 构造修改数据
    const updateData = {
      id: recordData.id,
      stepNo: -1,
      currentStep: "签约完成",
      nextStep: "无",
      finishTime: currentTime.value, // 当前时间作为完成时间
      // 其他需要修改的字段...
    };

    // 调用更新接口
    const updateRes = await updateAccraditationrecord(updateData);
    if (updateRes.code === 200) {
      ElMessage.success("审批记录修改成功");
      return true;
    } else {
      ElMessage.error(`修改失败：${updateRes.msg || "未知错误"}`);
      return false;
    }
  } catch (error) {
    console.error("修改审批记录出错：", error);
    ElMessage.error("修改失败，请重试");
    return false;
  }
};
// 组件卸载时清除定时器（避免内存泄漏）
onUnmounted(() => {
  if (timer) clearInterval(timer);
});
// 9. 向父组件发送事件
const emit = defineEmits(["goBack", "submitSuccess"]);
const handleGoBack = () => {
  emit("goBack");
};

// 10. 提交表单处理函数
const handleSubmit = async () => {
  // 校验必填项
  const isContractNameValid = checkRequired(contractName.value, "合同名称");
  const isSignDateValid = checkRequired(signDate.value, "签约日期");
  const isImageValid = checkRequired(imageUrl.value, "上传合同");
  // 校验手机号格式
  const isPhoneValid = checkPhoneFormat();

  // 有任何校验失败，阻止提交
  if (
    !isContractNameValid ||
    !isSignDateValid ||
    !isImageValid ||
    !isPhoneValid
  ) {
    uploadHint.value = !isImageValid; // 控制上传提示显示
    return;
  }
  uploadHint.value = false; // 校验通过，隐藏上传提示

  // 确保合同状态已计算
  calculateContractStatus();

  // 构造提交数据（包含自动计算的合同状态）
  formInfo.value = {
    contractNo: contractNo.value,
    contractName: contractName.value,
    elderlyId: elderId,
    startDate: startDate.value,
    endDate: endDate.value,
    partyCName: thirdPartyName.value,
    partyCPhone: thirdPartyPhone.value,
    contractFile: imageUrl.value,
    // contractStatus: contractStatus.value, // 提交自动计算的状态
    signTime: signDate.value,
    creator: userStore.id,
  };
  try {
    // 调用添加合同接口
    await addContract(formInfo.value);
    updateApprovalRecord(recordData.value);
    ElMessage.success("合同签署成功！");
    console.log("提交数据（含状态）：", formInfo.value);
    emit("submitSuccess"); // 向父组件发送提交成功事件
  } catch (error) {
    ElMessage.error("提交失败，请重试！");
  }
};

// 11. 图片上传相关函数
// 触发文件选择
const selectFile = () => {
  fileInput.value.click();
};

// 处理文件选择：存储完整文件名
const handleFileChange = (e) => {
  const file = e.target.files[0];
  if (!file) return;
  selectedFile.value = file;
  selectedFileName.value = file.name; // 存储完整文件名（不省略）
  e.target.value = ""; // 允许重复选择同一文件
  uploadFile(); // 触发上传
};

// 核心：文件上传逻辑
const uploadFile = async () => {
  if (!selectedFile.value) {
    ElMessage.warning("请选择文件");
    return;
  }

  // 构建FormData（文件上传格式）
  const formData = new FormData();
  formData.append("file", selectedFile.value, selectedFile.value.name);

  // 从Cookie获取Token（鉴权用）
  const token =
    document.cookie
      .split("; ")
      .find((row) => row.startsWith("Admin-Token="))
      ?.split("=")[1] || "";
  if (!token) {
    ElMessage.error("未获取到Token，请重新登录");
    return;
  }

  try {
    const response = await axios({
      method: "POST",
      url: "http://localhost:8080/common/upload",
      data: formData,
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": `multipart/form-data; boundary=${formData._boundary}`,
      },
      onUploadProgress: (e) => {
        // 实时更新上传进度
        progress.value = Math.round((e.loaded / e.total) * 100);
      },
    });

    if (response.data.code === 200) {
      imageUrl.value = response.data.url; // 存储上传后的图片URL
      uploadHint.value = false; // 隐藏上传提示
      console.log("文件上传成功，URL为：", imageUrl.value);
      console.log("上传的完整文件名：", selectedFileName.value);
      ElMessage.success("上传成功");
      progress.value = 0; // 重置进度条
    } else {
      ElMessage.error(`上传失败：${response.data.msg}`);
      selectedFileName.value = ""; // 上传失败，清空文件名
      progress.value = 0;
    }
  } catch (error) {
    console.error("上传错误详情：", error);
    const errorMsg = error.response?.data?.msg || "后端接口异常";
    ElMessage.error(`上传失败：${errorMsg}`);
    selectedFileName.value = ""; // 上传失败，清空文件名
    progress.value = 0;
  }
};

// 核心：预览图片（新页面打开）
const previewImage = () => {
  if (!imageUrl.value) {
    ElMessage.warning("无预览图片");
    return;
  }
  // 在新浏览器窗口打开图片（实现“其他页面显示”需求）
  window.open(imageUrl.value, "_blank");
};
</script>
  
  <style scoped>
/* 整体布局样式 */
.test-step-content {
  display: flex;
  flex-direction: column;
  min-height: 600px;
  padding: 20px;
}

.content-wrapper {
  display: flex;
  gap: 20px;
  margin-bottom: 80px;
}

/* 左侧表单区域样式 */
.left-content {
  flex: auto;
  display: flex;
  align-items: flex-start;
  padding-top: 16px;
}

.sign-container {
  width: 100%;
  max-width: 700px;
  font-size: 14px;
  color: #333;
}

.sign-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}

.sign-module {
  background: #fff;
  border: 1px solid #e5e6eb;
  border-radius: 6px;
  padding: 18px 20px;
  margin-bottom: 24px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.sign-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.sign-tag {
  width: 22px;
  height: 22px;
  background: #ec808d;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  border-radius: 50%;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
}

.sign-info {
  font-size: 16px;
  font-weight: bold;
}

/* 表单行样式 */
.form-row {
  display: flex;
  align-items: flex-start; /* 改为顶部对齐，避免按钮与标签基线不一致 */
  margin-bottom: 16px;
  padding-top: 5px; /* 统一行内元素顶部间距 */
}

.form-label {
  width: 120px;
  text-align: right;
  margin-right: 12px;
  font-weight: 500;
  padding-top: 5px; /* 标签文字向下微调，与输入框对齐 */
}

.form-label-required {
  width: 120px;
  text-align: right;
  margin-right: 12px;
  font-weight: 500;
  padding-top: 5px; /* 标签文字向下微调，与输入框对齐 */
}

.form-label-required::before {
  content: "*";
  color: #f5222d;
  margin-right: 4px;
}

.form-value {
  flex: 1;
  margin-top: 8px;
  color: #666;
}

/* 图片上传区域样式 - 核心修改 */
.upload-container {
  flex: 1; /* 使用flex布局填充剩余空间，与其他输入框对齐 */
  margin-left: 0; /* 移除左侧固定margin，改为flex布局控制 */
  padding-top: 0; /* 移除顶部padding，通过form-row统一控制 */
}

.hidden {
  display: none;
}

/* 文件名+预览按钮组合样式：显示完整文件名 */
.file-info-group {
  display: flex;
  align-items: center;
  margin-top: 10px;
  font-size: 14px;
  color: #666;
  flex-wrap: wrap; /* 文件名过长时自动换行，避免溢出 */
  width: 240px; /* 与按钮宽度一致 */
}

.uploaded-file-name {
  max-width: 180px; /* 限制文件名宽度，给预览按钮留出空间 */
  word-break: break-all; /* 允许文件名内换行 */
}

/* 上传提示样式 */
.upload-hint {
  color: #f5222d;
  font-size: 12px;
  margin: 5px 0 0 0;
  padding: 0;
  width: 240px; /* 与按钮宽度一致 */
}

/* 右侧操作记录区域样式 */
.right-content {
  max-width: 400px;
  flex: 1;
}

.operation-record-card {
  width: 100%;
  min-height: 300px;
  padding: 16px;
  box-sizing: border-box;
}

.record-time {
  width: 110px;
  text-align: right;
  color: #999;
  font-size: 13px;
}

.record-list {
  list-style: none;
  padding: 0;
  margin: 0;
  min-height: 700px;
  max-height: 440px;
  overflow-y: auto;
}

.record-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  font-size: 14px;
}

.record-icon {
  width: 14px;
  height: 8px;
  border-radius: 50%;
  background-color: #409eff;
  margin-right: 6px;
  margin-top: 6px;
}
/* 底部按钮组样式 */
.btn-group {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 10;
  width: 100%;
  padding: 16px 20px;
  background-color: #fff;
  border-top: 1px solid #eee;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
}

.mr-3 {
  margin-right: 12px;
}

/* 合同状态样式 */
.status-pending {
  color: #faad14;
  font-weight: 500;
}

.status-active {
  color: #52c41a;
  font-weight: 500;
}

.status-expired {
  color: #f5222d;
  font-weight: 500;
}
.record-content {
  width: 300px;
  margin: 0 12px;
  color: #333;
}
.record-content p {
  margin-top: -4px;
}
.record-time {
  width: 220px;
  text-align: right;
  color: #999;
  font-size: 13px;
}
</style>